let { projectRootPath } = require("../../util/path/index.js");
let {
  executeSql,
  transaction,
  getTotal,
  getByPagination,
  removeByUuid,
  getAll,
} = require(`${projectRootPath}/mysql/index.js`);
let { getUuid } = require(`${projectRootPath}/util/uuid/index.js`);
let { getCurrentDatetime } = require(
  `${projectRootPath}/util/datetime/index.js`,
);
let { getUserByAll, editUserByUuid } = require(
  `${projectRootPath}/service/user/index.js`,
);

// 根据 polylineUuid 获取 Patrol
async function getPatrolByPolylineUuid(data) {
  let { polylineUuid } = data;
  let whereAll = `where polylineUuid='${polylineUuid}'`;
  return await transaction(async (connection) => {
    let list = await getByPagination(
      connection,
      "PatrolTable",
      "opDatetime",
      whereAll,
      10,
      1,
    );
    let total = await getTotal(
      connection,
      "PatrolTable",
      "opDatetime",
      whereAll,
    );
    return { list, total };
  });
}

// 创建 Patrol
async function createPatrol(data) {
  let { userUuid, polylineUuid, poly } = data;
  return await transaction(async (connection) => {
    let currentDatetime = getCurrentDatetime();
    let polyline = [poly];
    let polylineJson = JSON.stringify(polyline);
    let sql = `insert into PatrolTable (uuid, userUuid, polylineUuid, polyline, opDatetime) values ('${getUuid()}', '${userUuid}', '${polylineUuid}', '${polylineJson}', '${currentDatetime}')`;
    await executeSql(connection, sql);
    return polyline;
  });
}

// 更新 Patrol
async function editPatrol(data) {
  let { uuid, polyline, poly } = data;
  return await transaction(async (connection) => {
    let max = 0.00004;
    let lastPloy = polyline[polyline.length - 1];
    if (
      Math.abs(poly.longitude - lastPloy.longitude) > max ||
      Math.abs(poly.latitude - lastPloy.latitude) > max
    ) {
      polyline.push(poly);
      let polylineJson = JSON.stringify(polyline);
      let sql = `update PatrolTable set polyline='${polylineJson}' where uuid='${uuid}'`;
      await executeSql(connection, sql);
    }
    return polyline;
  });
}

// 创建或更新 Patrol
async function createOrEditPatrol(data) {
  let { userUuid, polylineUuid, poly } = data;
  return await transaction(async (connection) => {
    let currentDatetime = getCurrentDatetime();
    let tempPatrol = await getPatrolByPolylineUuid({ polylineUuid });
    if (tempPatrol.list.length > 0) {
      // 修改
      let patrol = tempPatrol.list[0];
      let polyline = await editPatrol({
        uuid: patrol.uuid,
        polyline: JSON.parse(patrol.polyline),
        poly,
      });
      return polyline;
    } else {
      // 创建
      let polyline = await createPatrol({ userUuid, polylineUuid, poly });
      return polyline;
    }
  });
}

// 根据筛选项获取 Patrol 列表
async function getPatrolWithFormData(data) {
  let { datetimeRange, userUuidList } = data;
  let allWhere = [];
  if (datetimeRange?.length === 2) {
    let where = `PatrolTable.opDatetime between '${datetimeRange[0]}' and '${datetimeRange[1]}'`;
    allWhere.push(where);
  }
  if (userUuidList?.length > 0) {
    let tempWhere = [];
    for (let i = 0; i < userUuidList.length; i++) {
      let userUuid = userUuidList[i];
      let where = `PatrolTable.userUuid='${userUuid}'`;
      tempWhere.push(where);
    }
    if (tempWhere.length > 0) {
      tempWhere = `(${tempWhere.join(" or ")})`;
      allWhere.push(tempWhere);
    }
  }
  if (allWhere.length === 0) {
    allWhere = "";
  } else {
    allWhere = "where " + allWhere.join(" and ");
  }
  return await transaction(async (connection) => {
    let sql = `select 
                        PatrolTable.polyline as polyline, UserTable.uuid as userUuid, UserTable.avatar as avatar, UserTable.name as name
                        from PatrolTable left join UserTable on PatrolTable.userUuid=UserTable.uuid ${allWhere} order by PatrolTable.opDatetime`;
    let list = await executeSql(connection, sql);
    return { list };
  });
}

module.exports = {
  createOrEditPatrol,
  getPatrolWithFormData,
};
